import { dest } from "gulp";

import dartSass from "sass";
// @ts-ignore
import gulpSass from "gulp-sass";
// @ts-ignore
import cleanCss from "gulp-clean-css";
// @ts-ignore
import autoPrefixer from 'gulp-autoprefixer';
import { FileTask } from "../utils/baseTaskClass";

export const Sass = gulpSass(dartSass);

export class SassCompile extends FileTask {
  private readonly compress: boolean;
  private readonly prefixer: boolean;

  constructor(path: string | string[], {
    compress = true,
    prefixer = true
  } = {}) {
    super(path);
    this.compress = compress;
    this.prefixer = prefixer;
  }

  prefixerHandle(css = null) {
    return (css ?? this.instance)?.pipe(autoPrefixer({
      cascade: false,
    }));
  }

  compressHandle(css = null) {
    return (css ?? this.instance)?.pipe(cleanCss({
      // 压缩级别2（最高级别）
      level: 2,
      // 增加换行符以提高可读性
      format: "keep-breaks"
    }));
  }

  compileHandle() {
    return this.instance.pipe(Sass().on("error", Sass.logError));
  }

  exec(out: string) {
    let sass = this.compileHandle();
    // 浏览器前缀兼容处理
    this.prefixer && (sass = this.prefixerHandle(sass));
    // 样式压缩处理
    this.compress && (sass = this.compressHandle(sass));
    return sass?.pipe(dest(out));
  }
}
